/*************************************************************
 * Title: ClassHelper.java
 * Description: 
 * Author: Huang Shaobin
 * Email: huangshaobin@qtt.cn
 * CreateTime: Feb 8, 2013 4:02:35 PM
 * Copyright © 北京全天通信息咨询服务有限公司 All right reserved
 ************************************************************/
package snow.core.toolkit;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

/**
 *
 */
public class ClassHelper {

	/** Prefix for jdk dynamic proxy class names: "$Proxy" */
	public static final String JDK_DYNAMIC_PROXY_CLASS_PREFIX = "$Proxy";

	/** Suffix for array class names: "[]" */
	public static final String ARRAY_SUFFIX = "[]";

	/** Prefix for internal array class names: "[" */
	public static final String INTERNAL_ARRAY_PREFIX = "[";

	/** Prefix for internal non-primitive array class names: "[L" */
	public static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L";

	/** The package separator character '.' */
	public static final char PACKAGE_SEPARATOR = '.';

	/** The inner class separator character '$' */
	public static final char INNER_CLASS_SEPARATOR = '$';

	/** The CGLIB class separator character "$$" */
	public static final String CGLIB_CLASS_SEPARATOR = "$$EnhancerByCGLIB$$";

	/** The Javassist class separator character "$$" */
	public static final String JAVASSIST_CLASS_SEPARATOR = "_$$_javassist_";

	/** The ".class" file suffix */
	public static final String CLASS_FILE_SUFFIX = ".class";

	public static <E> E cast(Class<E> targetClass, Object source) {
		if (targetClass != null && source != null && targetClass.isAssignableFrom(source.getClass())) {
			return targetClass.cast(source);
		}
		return null;
	}

	public static Class<?> getSubclassFrom(Class<?>[] classes, Class<?> superClass) {
		if (ArrayUtils.isEmpty(classes) || superClass == null) {
			return null;
		}
		for (final Class<?> subclass : classes) {
			if (subclass != null && superClass.isAssignableFrom(subclass)) {
				return subclass;
			}
		}
		return null;
	}

	public static boolean isCglibProxy(Class<?> targetClass) {
		return StringUtils.contains((targetClass == null ? null : targetClass.getName()), CGLIB_CLASS_SEPARATOR);
	}

	public static boolean isDynamicProxy(Class<?> targetClass) {
		return isCglibProxy(targetClass) || isJavassistProxy(targetClass);
	}

	public static boolean isJavassistProxy(Class<?> targetClass) {
		return StringUtils.contains((targetClass == null ? null : targetClass.getName()), JAVASSIST_CLASS_SEPARATOR);
	}

	public static boolean isJdkDynamicProxy(Class<?> targetClass) {
		return StringUtils.contains((targetClass == null ? null : targetClass.getName()), JDK_DYNAMIC_PROXY_CLASS_PREFIX);
	}

}
